package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.qf.service.AlipayService;
import com.qf.utils.AlipayUtils;
import com.qf.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by 54110 on 2021/5/12.
 */
@RestController
@RequestMapping("/ali")
public class AlipayController {

    @Autowired
    AlipayService alipayService;
    @Autowired
    JwtUtils jwtUtils;

    @RequestMapping("/pay")
    public String pay(@RequestBody Map map, HttpServletRequest request){

        List ids =(List) map.get("ids");

        Cookie[] cookies =  request.getCookies();
        String token="";
        if (cookies!=null){
            for (Cookie cookie: cookies
                    ) {
                if (cookie.getName().equals("token")){
                    token=cookie.getValue();
                }
            }
        }
        Map maps = jwtUtils.varferToken(token);
        String userid = maps.get("id").toString();
        System.out.println(ids);
        return alipayService.pay(ids,userid);
    }


    @RequestMapping("/notifyPay")
    public void notfiyPay(HttpServletRequest request) throws AlipayApiException {
        AlipayUtils alipayUtils = new AlipayUtils();
        Map<String, String> stringStringMap =alipayUtils.convertRequestParamsToMap(request);
        boolean  signVerified = AlipaySignature.rsaCheckV1(stringStringMap, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAol4SrTwjB6RqSYQKWGiGopysy9KoHluqrsasGqDZWBm8Q4WlDYXpRpV7C53fqbChz/p/VwdGpb+bDSZU9pLEaSCzZTX6JqEeFo2fQav4mRVIY1FPgqOJ5Mn4AN/dB7j45Qy9wrIKh6+nP3dvDiN4wrHiobj4cl8Xb4vxbI3bvbj2SFYeL6u8iO49Hi4oXHvNaNzoKw8tl2hkI8N5sWU4LZAdT8odCSdpWwoMRvAapN+Doa4ceRgBmSc9D6l2qfz8Y0DIjd9wrs2fAc0XUUxb+JG1p5wGnzDagaNxFO8YkfeKlnaLtQ2ELQ2cy25db6sdNihIvXs6J3RzaU9kB4lHZwIDAQAB", "utf-8", "RSA2");  //调用SDK验证签名
        if (signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println(stringStringMap);
            //判断如果支付钱数准确，修改订单状态，置为以支付 状态
            String out_trade_no = stringStringMap.get("out_trade_no");
            String trade_status = stringStringMap.get("trade_status");
            //使用订单号去数据库查询楚该订单，并且修改状态
            alipayService.updateStatus(out_trade_no,trade_status);
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }

    }


}
